// 获取健康数据
import axios from "axios";

const parseVitalSigns = (detail) => {
    try {
        // 增加安全判断，确保detail存在
        if (!detail) return {bloodPressure: null, bloodSugar: null, heartRate: null};

        const parts = detail.split('|');
        // 更安全的数组解构，避免undefined值
        const bloodPressure = parts[3] || '';
        const bloodSugar = parts[4] || '';
        const heartRate = parts[5] || '';
        const parts2 =bloodPressure.split('/');
        const s = parts2[0]||'';
        const d =  parts2[1]||'';

        return {
            systolic:toValidNumber(s),
            diastolic:toValidNumber(d),
            bloodPressure: toValidNumber(bloodPressure),
            bloodSugar: toValidNumber(bloodSugar),
            heartRate: toValidNumber(heartRate)
        };
    } catch (error) {
        console.error('解析健康数据失败:', error);
        return {bloodPressure: null, bloodSugar: null, heartRate: null};
    }
};

const toValidNumber = (value) => {
    // 处理空字符串和无效值
    if (value === '' || value === null || value === undefined) return null;
    const num = parseFloat(value);
    return Number.isFinite(num) ? num : null;
};

export const getHealthData = (userId) =>
    axios.get(`/api/healthData/getDataToAnalysis/${userId}`).then(res => {
        console.log('数据分析 接口原始响应:', res);

        // 确保从res.data中获取数组数据
        // const dataArray = res.data || [];
        const dataArray = Array.isArray(res.data) ? res.data : [];
        return dataArray.map(item => {
            const parsedData = parseVitalSigns(item?.detail);
            return {
                date: item.recordDate,
                ...parsedData  // 正确展开解析后的健康数据
            };
        });
    });